Explain the concept of portals in React.
Explain the concept of portals in React.
581
05-Oct-2023
Updated on 06-Oct-2023
Aryan Kumar
06-Oct-2023Portals in React are a way to render a component's content in a different part of the DOM (Document Object Model) hierarchy than where the component itself is rendered. Portals provide a mechanism to break out of the normal parent-child hierarchy in React and render a component's content into a different DOM element that may not be a direct child of the component's parent. This can be useful for scenarios like modals, tooltips, and other UI elements that need to be rendered at a higher level in the DOM hierarchy.
Here's a simplified explanation of the concept of portals in React:
Normal React Rendering:
In a typical React application, when you render a component, its output is placed within the DOM element where the component is mounted. For example, if you render a modal component within another component, the modal's content will be a child of the parent component's DOM element.
Portals:
Portals allow you to render a component's content into a different DOM element outside of the component's parent hierarchy. This means you can render a component's content at a higher level in the DOM, often directly under the body or any other element of your choice.
Use Cases:
Portals are particularly useful for scenarios like modals, tooltips, context menus, and any UI element that should appear above all other content on the page. By using a portal, you can ensure that these elements are rendered in the desired location and don't interfere with the CSS or event handling of other components.
Here's a simplified example of how you can use a portal in React:
In this example, the MyModal component uses createPortal to render its content into an element with the id portal-root, which can be anywhere in the DOM hierarchy. This allows the modal to appear above all other content on the page, even though it's defined within the App component.